<template>
  <view class="details">
    <view class="header">
      <view class="realtimeChart">
        <RealtimeChart :realtime="realtime" />
      </view>
    </view>

    <view class="main">
      <view class="stockChart">
        <StockChart
          :watermark="`${cycle.list[cycle.current]?.title} K`"
          :details="details"
          :zoom="zoom"
          @stockChartMaClick="stockChartMaClick"
        />
      </view>
    </view>

    <view class="footer">
      <swiper class="swiper" @change="swiperChange">
        <swiper-item class="swiper-item">
          <scroll-view class="scrollView" :scroll-y="true" :show-scrollbar="false">
            <view class="cycle">
              <view class="list">
                <view
                  class="item"
                  v-for="(item, index) in cycle.list"
                  :key="item.ktype"
                  :class="{ current: cycle.current == index }"
                  @click="cycleClick({ item, index })"
                >
                  <view class="technologyChart">
                    <TechnologyChart
                      :caption="{
                        title: item.title,
                        k: item.details.analysis.latestKd.k?.toFixed(1),
                        percentage: item.details.analysis.latestMaDifference.percentage?.toFixed(
                          2
                        ),
                      }"
                      :details="item.details"
                    />
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
        </swiper-item>
        <swiper-item class="swiper-item">
          <view class="modifier">
            <view class="editTransaction">
              <view class="list">
                <view
                  class="item"
                  v-for="(item, index) in modifierLatest.transaction"
                  :key="index"
                  :class="{ current: modifier.current == index }"
                >
                  <view class="title">{{ index }}：</view>
                  <view class="input" @click="modifier.current = index">{{ item }}</view>
                </view>
              </view>
            </view>
            <view class="pushTransaction">
              <button @click="pushTransaction">加入一条K线</button>
            </view>
          </view>
        </swiper-item>
      </swiper>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, watch, onUnmounted, nextTick } from "vue";

import $u from "@/u";
import $api from "@/api/index";

import RealtimeChart from "@/components/RealtimeChart.vue";
import StockChart from "@/components/StockChart.vue";
import TechnologyChart from "@/components/TechnologyChart.vue";

const props = defineProps({
  code: {
    type: String,
    default: "000001",
  },
  type: {
    type: String,
    default: "stock",
  },
});

let timer = null;

const updateTime = ref(+new Date());
const realtime = reactive({});
const details = reactive({});
const zoom = ref(false);

const cycle = reactive({
  current: 4,
  list: [],
});

const modifier = reactive({
  current: "",
  list: [],
});

const detailsLatestTransaction = computed(() => details.transaction?.at(-1));
const modifierLatest = computed(() => modifier.list?.at(-1) || {});

watch(
  updateTime,
  async () => {
    let { code = "", type = "" } = props;
    let { data } = await $api.stock.realtime({ code, type });
    Object.assign(realtime, data);
    if (data.stockStatus == "已收盘") {
      clearInterval(timer);
      return false;
    }
    timer = setTimeout(() => (updateTime.value = +new Date()), 3000);
  },
  { immediate: true }
);

watch(
  () => cycle.current,
  async () => {
    await nextTick();
    getDetails();
  },
  { immediate: true }
);

const getDetails = async () => {
  let { code = "", type = "" } = props;
  let { ktype = "" } = cycle.list[cycle.current] || {};
  let latest = 60;

  let modifierList = modifier.list;

  let { data } = await $api.stock.details({
    code,
    type,
    ktype,
    latest,
    modifierList,
  });

  Object.assign(details, data.details);

  if (data.cycle.length) {
    cycle.list = data.cycle;
  }
};

const stockChartMaClick = async ({ ma, price }) => {
  if (!modifier.current) return false;
  modifierLatest.value.transaction[modifier.current] = price;
  $u.toast({ title: `ma${ma}：${price}` });
  await getDetails();
};

const cycleClick = ({ index }) => {
  cycle.current = index;
};

const swiperChange = ({ target }) => {
  let { current } = target;
  if (current == 0) {
    resetModifier();
    zoom.value = false;
  } else if (current == 1) {
    if (modifier.list.length) return false;
    let { index, open, close, high, low } = detailsLatestTransaction.value;
    let transaction = { index, open, close, high, low };
    modifier.list.push({ type: "edit", transaction });
    zoom.value = true;
  }
};

const pushTransaction = () => {
  let index = detailsLatestTransaction.value?.index;

  modifier.list.push({
    type: "push",
    transaction: { index: index + 1, open: -1, close: -1, high: -1, low: -1 },
  });

  getDetails();
};

const resetModifier = () => {
  modifier.list = [];
  modifier.current = "";
  getDetails();
};

onUnmounted(() => {
  clearInterval(timer);
});
</script>

<style lang="scss" scoped>
.details {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #161922;

  > .header {
    $height: 400upx;
    height: $height;
    border-bottom: 2upx solid #000;

    > .realtimeChart {
      height: $height;
    }
  }

  > .main {
    flex: 1;
    position: relative;
    border-bottom: 2upx solid #000;

    > .stockChart {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
    }
  }

  > .footer {
    $height: 110upx;
    $count: 6;
    $totalHeight: $count * $height;
    height: $totalHeight;

    > .swiper {
      height: $totalHeight;

      .swiper-item {
        .scrollView {
          height: $totalHeight;
          .cycle {
            > .list {
              > .item {
                position: relative;
                height: $height;
                border-bottom: 2upx solid #000;

                > .technologyChart {
                  height: $height;
                }

                &.current {
                }
              }
            }
          }
        }

        .modifier {
          padding: 20upx;
          color: #fff;
          > .editTransaction {
            > .list {
              display: flex;
              flex-wrap: wrap;
              > .item {
                display: flex;
                margin-bottom: 20upx;
                width: 50%;
                line-height: 72upx;
                > .title {
                  width: 100upx;
                  text-align: right;
                }
                > .input {
                  margin-left: 10upx;
                  width: 180upx;
                  border: 1px solid #666;
                  border-radius: 12upx;
                  text-align: center;
                }
                &.current {
                  > .input {
                    border-color: $color1;
                    color: $color1;
                  }
                }
              }
            }
          }

          > .pushTransaction {
            margin-top: 40upx;
            > button {
              background-color: $color1;
              color: #fff;
            }
          }
        }
      }
    }
  }
}
</style>
